package SAXParser;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Set;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class SingleSAX extends DefaultHandler{
	
	static StringBuilder buffer = new StringBuilder();
	private boolean flagK = false;
	private boolean flagS = false;
	private boolean flagV = false;
	
	private RankPost post = new RankPost();
	private static ArrayList<RankPost> posts = new ArrayList<RankPost>();
	
	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		// TODO Auto-generated method stub
		if(qName.equals("K")) {
			post = new RankPost();
			flagK  = true;
		}
		else if(qName.equals("S")) {
			flagS= true;
		}
		else if(qName.equals("V")) {
			flagV = true;
		}
		
	}
	
	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		// TODO Auto-generated method stub
		if(flagK) {
			post.setK(new String(ch, start, length));
			//System.out.println(data);
		}
		else if(flagS) {
			post.setS(new String(ch,start,length));
		}
		else if(flagV) {
			post.setV(new String(ch,start,length));
		}
		
	}
	
	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		if(qName.equals("K")) {
			flagK = false;
		}
		else if(qName.equals("S")) {
			flagS = false;
		}
		else if(qName.equals("V")) {
			flagV = false;
			posts.add(post);
		}
		
		
	}
	
	public static void main(String[] args) throws ParserConfigurationException,SAXException,IOException{
		SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
		DefaultHandler dh = new SingleSAX();
		parser.parse("http://openapi.naver.com/search?key=041d0a656b29e0b0df2eb2a06ea605ac&query=nexearch&target=rank", dh);
		System.out.println(posts);
		//System.out.println(buffer);
		
	}
}
